/*
 * File   : includes/history.h
 * Author : Nandakiran Kirubanandan
 *
 * This file contains the function declarations for maintaining a history
 * of strings. (back/forward)
 *
 */

#include "history.h"
#include "linkedlist.h"

docHistory::docHistory() {
	list = new linkedlist();
	current = list->first;
}

docHistory::~docHistory() {
	list->removeAll();
	delete list;
}
bool docHistory::isBack() {
	return (current!=list->first);
}

bool docHistory::isForward() {
	return (current!=list->last);
}

char* docHistory::getForward() {
	if (!isForward())
		return NULL;
	current=current->next;
	return strdup(current->data);
}

char* docHistory::getBack() {
	if (!isBack())
		return NULL;
	current=current->prev;
	return strdup(current->data);
}

char* docHistory::getCurrent() {
	if (current!=NULL)
		return strdup(current->data);
	return NULL;
}
void docHistory::add(char *url) {
	// if same as current url then dont modify history
	if ((current!=NULL) && (strcmp(current->data,url)==0))
		return;

	// Remove all "history" elements which are forward of current
	// and then add the new url at the end.

	if (isForward()) {
		struct list *tmp,*tmp2;
		tmp=current->next;
		current->next=NULL;
		list->last=current;
		while (tmp!=NULL) {
			tmp2=tmp;
			tmp=tmp->next;
			free(tmp2->data);
			free(tmp2);
		}
	}
	list->add(url);
 	current=list->last;	
//	printf("List : %s \n",list->toString());
}

